package com.breeze.blockchain.common.interceptor;

import cn.hutool.core.util.StrUtil;
import com.breeze.blockchain.auth.AuthContextHolder;
import com.breeze.blockchain.auth.util.AdminUserUtil;
import com.breeze.blockchain.auth.util.AppUserUtil;
import com.breeze.blockchain.service.AdminService;
import com.breeze.blockchain.service.UserService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.util.Objects;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

/**
 * @author breeze
 */
@Component
@Slf4j
public class UserContextInterceptor implements HandlerInterceptor {

  @Resource UserService userService;
  @Resource AdminService adminService;

  @Override
  public boolean preHandle(
      HttpServletRequest request, @NonNull HttpServletResponse response, @NonNull Object handler) {
    var token = request.getHeader("Authorization");
    if (StrUtil.isEmpty(token)) {
      return true;
    }
    if (request.getRequestURI().startsWith("/api/admin")) {
      var loginIdByToken = AdminUserUtil.getLoginIdByToken(token);
      if (Objects.isNull(loginIdByToken)) {
        return true;
      }
      var loginId = Long.parseLong(String.valueOf(loginIdByToken));
      AuthContextHolder.SYS_USER.set(adminService.getById(loginId));
    } else if (request.getRequestURI().startsWith("/api/app")) {
      var loginIdByToken = AppUserUtil.getLoginIdByToken(token);
      if (Objects.isNull(loginIdByToken)) {
        return true;
      }
      var loginId = Long.parseLong(String.valueOf(loginIdByToken));
      AuthContextHolder.APP_USER.set(userService.getById(loginId));
    }
    return true;
  }

  @Override
  public void afterCompletion(
      @NonNull HttpServletRequest request,
      @NonNull HttpServletResponse response,
      @NonNull Object handler,
      Exception ex) {
    // 如果ThreadLocal中用完的信息不进行删除，会有内存泄漏的风险
    AuthContextHolder.SYS_USER.remove();
    AuthContextHolder.APP_USER.remove();
  }
}
